<template>
	<view class="container">
		<view class="m-title">
			收货信息
			<text @click="copy" v-if="receive_name">点击复制</text>
		</view>
		<view class="main" v-if="receive_name">
			<view class="p">
				<text>收件人</text>
				{{ receive_name }}
			</view>
			<view class="p">
				<text>联系电话</text>
				{{ receive_mobile }}
			</view>
			<view class="p">
				<text>收件地址</text>
				{{ receive_address }}
			</view>
		</view>
		<view class="select-address" @click="getReceiverAddress" v-else>从地址库选择</view>

		<view class="m-title">商品信息</view>
		<view class="list-goods">
			<view class="item u-flex u-col-top u-row-between" v-for="(item, index) in list" :key="index">
				<view class="img">
					<image :src="http + item.image" mode="aspectFill"></image>
				</view>
				<view class="con">
					<view class="title u-line-1">
						{{ item.title }}
					</view>
					<view class="tips">
						<text v-for="(item2, index2) in item.spec" :key="index2">{{ item2 }}</text>
					</view>
				</view>
				<view class="r">
					<view class="price">{{ item.price - item.mountings_price }}元</view>
					<view class="num">×{{ item.num }}</view>
				</view>
			</view>
			<view class="total">
				<text>商品金额：¥{{ total1(list) }}</text>
				<text>服务费：¥{{ total2(list) }}</text>
				<text>合计：¥{{ total3(list) }}</text>
			</view>
		</view>

		<view class="m-title">备注</view>
		<view class="textarea">
			<textarea v-model="notes" placeholder="请填写备注"></textarea>
		</view>

		<view class="footer">
			<view class="btn" @click="submit">立即支付</view>
		</view>

		<u-popup :show="show" :round="10" mode="center" closeable @close="show = false">
			<view class="pop">
				<view class="title">歇业公告</view>
				<view style="overflow-y: auto; height: 300rpx" class="" v-html="ggdata.xieye_remark"></view>
			</view>
		</u-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			http: this.$imgUrl,
			notes: '',
			list: [],
			// 地址信息
			receive_address: '',
			receive_mobile: '',
			receive_name: '',
			receive_prov: '',
			receive_city: '',
			receive_area: '',
			receive_detail_address: '',
			receive_city_code: '',
			address_id: 0,

			show: false,
			ggdata: {},
			orderInfo: {}, // 存储订单信息
			entityIds: []
		};
	},
	onLoad() {
		my.setNavigationBar({
			frontColor: '#000',
			backgroundColor: '#fff'
		});
		this.list = uni.getStorageSync('cart2') || [];
		this.systemConfig();

		this.$http.post('/api/sell_order/template', {}).then((res) => {
			this.entityIds = res.data;
		});
	},
	computed: {
		total1() {
			return (list) => {
				return list.reduce((acc, cur) => acc + parseInt(cur.num) * parseFloat(cur.price), 0).toFixed(2);
			};
		},
		total2() {
			return (list) => {
				// 计算总商品数量
				const totalQuantity = list.reduce((acc, cur) => acc + parseInt(cur.num || 0), 0);

				// 获取运费阈值（假设所有商品的 product_num 相同，取第一个）
				const thresholdNum = list[0]?.express?.product_num ? parseInt(list[0].express.product_num) : 0;

				// 如果总商品数量超过阈值，运费为0
				if (totalQuantity >= thresholdNum) {
					return '0.00';
				}

				// 否则计算总运费
				return list
					.reduce((acc, cur) => {
						if (!cur.express) return acc;
						const productNum = parseInt(cur.num) || 0;
						const expressPrice = parseFloat(cur.express.express_price) || 0;
						return acc + productNum * expressPrice;
					}, 0)
					.toFixed(2);
			};
		},
		total3() {
			return (list) => {
				// 商品总金额
				const productTotal = parseFloat(this.total1(list));

				// 运费
				const expressTotal = parseFloat(this.total2(list));

				// 配件扣减总金额
				const mountingsDeduct = list.reduce((acc, cur) => acc + parseInt(cur.num) * parseFloat(cur.mountings_price || 0), 0);

				// 验货费扣减总金额
				const deductTotal = list.reduce((acc, cur) => acc + parseInt(cur.num) * parseFloat(cur.deduct_price || 0), 0);

				// 最终应付金额 = 商品总金额 - 配件扣减 - 验货费扣减 + 运费
				const finalAmount = productTotal - mountingsDeduct - deductTotal + expressTotal;

				return finalAmount.toFixed(2);
			};
		}
	},
	methods: {
		getReceiverAddress() {
			my.getAddress({
				success: (res) => {
					console.log('地址获取成功', res);
					if (res.resultStatus === '9000') {
						const addressInfo = res.result;
						// 更新地址信息
						this.receive_name = addressInfo.fullName || addressInfo.fullname;
						this.receive_mobile = addressInfo.mobilePhone;
						this.receive_prov = addressInfo.prov;
						this.receive_city = addressInfo.city;
						this.receive_area = addressInfo.area;
						this.receive_detail_address = addressInfo.address;
						this.receive_address = addressInfo.prov + addressInfo.city + addressInfo.area + addressInfo.address;
					} else if (res.resultStatus === '6001') {
						console.log('用户取消了地址选择');
					}
				},
				fail: (err) => {
					console.log('地址获取失败', err);
					my.alert({ title: '获取地址失败，请稍后重试' });
				}
			});
		},
		copy() {
			let data = `${this.receive_name}  ${this.receive_mobile}  ${this.receive_address}`;
			uni.setClipboardData({
				data: data,
				success: () => {
					uni.showToast({
						title: '已复制',
						icon: 'none'
					});
				}
			});
		},
		systemConfig() {
			this.$http
				.post('/api/sell_order/address', {})
				.then((res) => {
					if (res.code == 1) {
						const addressData = res.data;
						// 设置完整的地址信息
						this.receive_name = addressData.fullname || addressData.receive_name;
						this.receive_mobile = addressData.mobilePhone || addressData.receive_mobile;
						this.receive_prov = addressData.prov;
						this.receive_city = addressData.city;
						this.receive_area = addressData.area;
						this.receive_detail_address = addressData.address;
						this.receive_city_code = addressData.city_code;
						this.address_id = addressData.id || 0;
						// 完整地址显示
						this.receive_address = [addressData.prov, addressData.city, addressData.area, addressData.address].filter(Boolean).join('');
					} else {
						// 如果接口没有返回地址数据，不显示地址信息，用户需要手动选择
						this.clearAddress();
					}
				})
				.catch((err) => {
					console.log('错误信息：', err);
					// 接口调用失败时，清空地址信息
					this.clearAddress();
				});
		},
		clearAddress() {
			this.receive_address = '';
			this.receive_mobile = '';
			this.receive_name = '';
			this.receive_prov = '';
			this.receive_city = '';
			this.receive_area = '';
			this.receive_detail_address = '';
			this.receive_city_code = '';
			this.address_id = 0;
		},
		submit() {
			if (this.ggdata.xieye_switch == '1') {
				this.show = true;
				return;
			}

			if (this.list.length == 0) {
				return;
			}

			// 检查地址是否填写
			if (!this.receive_name || !this.receive_mobile || !this.receive_address) {
				uni.showToast({
					title: '请先选择收货地址',
					icon: 'none'
				});
				return;
			}

			let order_price = this.total1(this.list);
			let express_price = this.total2(this.list); // 邮费
			let pay_price = this.total3(this.list); // 支付金额
			let mountings_price = this.list.reduce((acc, cur) => acc + parseInt(cur.num) * parseFloat(cur.mountings_price), 0).toFixed(2);

			let products = this.list.map((item) => {
				return {
					id: item.id,
					num: item.num,
					type: item.type,
					sell_spec: item.spec.toString(),
					price: item.price,
					mountings_price: item.mountings_price,
					mountings_text: item.mountings_text,
					my_dec_price: item.my_dec_price,
					ta_dec_price: item.ta_dec_price
				};
			});

			// 构建地址信息
			let addressInfo = {
				id: this.address_id || 0,
				fullname: this.receive_name,
				mobilePhone: this.receive_mobile,
				prov: this.receive_prov || '',
				city: this.receive_city || '',
				area: this.receive_area || '',
				address: this.receive_detail_address || this.receive_address,
				city_code: this.receive_city_code || ''
			};

			uni.showModal({
				title: '温馨提示',
				content: `确认支付 ¥${pay_price} 吗？`,
				success: (res) => {
					if (res.confirm) {
						// 先创建订单
						this.$http
							.post('/api/sell_order/createorder', {
								order_price: order_price,
								express_price: express_price,
								pay_price: pay_price,
								remark: this.notes,
								products: products,
								address: addressInfo
							})
							.then((res) => {
								if (res.code == 1) {
									this.payOrder(res.data.id);
								} else {
									uni.showToast({
										title: res.msg,
										icon: 'none'
									});
								}
							})
							.catch((err) => {
								console.log('错误信息：', err);
							});
					}
				}
			});
		},

		// 支付订单
		payOrder(id) {
			this.$http.post('/api/sell_order/pay ', { id: id }).then((res) => {
				if (res.code == 1) {
					// 调用支付宝支付
					my.tradePay({
						tradeNO: res.data.data.alipay_trade_create_response.trade_no, // 支付宝交易号
						success: (res) => {
							if (res.resultCode === '9000') {
								// 支付成功
								uni.showToast({
									title: '支付成功',
									icon: 'success'
								});
								uni.removeStorageSync('cart');
								uni.removeStorageSync('cart2');
								this.list = [];
								my.requestSubscribeMessage({
									entityIds: this.entityIds,
									success: (res) => {
										console.log('接口调用成功的回调', res);
										setTimeout(() => {
											uni.redirectTo({
												url: '/pages/index/listOrder1'
											});
										}, 500);
									},
									fail: (err) => {
										console.log('接口调用失败的回调', err);
										setTimeout(() => {
											uni.redirectTo({
												url: '/pages/index/listOrder1'
											});
										}, 500);
									}
								});
							} else {
								// 支付失败
								uni.showToast({
									title: '支付取消',
									icon: 'none'
								});
								uni.removeStorageSync('cart');
								uni.removeStorageSync('cart2');
								this.list = [];
								setTimeout(() => {
									uni.redirectTo({
										url: '/pages/index/listOrder1'
									});
								}, 500);
							}
						},
						fail: (err) => {
							console.log('支付失败', err);
							uni.showToast({
								title: '支付失败',
								icon: 'none'
							});
						}
					});
				}
			});
		}
	}
};
</script>

<style lang="less" scoped>
@color: #e31d21;

.pop {
	width: 630rpx;
	height: 431rpx;
	background: #fcfdff;
	border-radius: 40rpx;
	padding: 40rpx;
	box-sizing: border-box;
	.title {
		font-size: 40rpx;
		font-weight: bold;
		color: #000;
		text-align: center;
	}
}

.container {
	padding: 30rpx 30rpx 200rpx;

	.footer {
		position: fixed;
		background-color: #fff;
		left: 0;
		right: 0;
		padding: 20rpx 30rpx;
		z-index: 999;
		bottom: 0;

		.btn {
			width: 100%;
			height: 80rpx;
			text-align: center;
			border-radius: 40rpx;
			line-height: 80rpx;
			font-size: 32rpx;
			font-weight: 600;
			color: #fff;
			background-color: @color;
		}
	}

	.textarea {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 10rpx;

		textarea {
			width: 100%;
			height: 100rpx;
			font-size: 28rpx;
			color: #333;
		}
	}

	.list-goods {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 10rpx;

		.total {
			margin-top: 20rpx;
			height: 60rpx;
			line-height: 60rpx;
			font-size: 24rpx;
			text-align: right;
			color: #666;
			white-space: nowrap;

			text {
				margin-left: 20rpx;
			}
		}

		.item {
			padding: 10rpx 0;
			border-bottom: 2rpx solid #eee;

			.img {
				width: 112rpx;
				height: 180rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.con {
				flex: 1;
				padding: 0 20rpx;
				width: 1rpx;

				.title {
					font-size: 28rpx;
					color: #333;
				}

				.tips {
					text {
						color: #999;
						font-size: 24rpx;
						margin: 10rpx 10rpx 0 0;
					}
				}
			}

			.r {
				text-align: right;

				.price {
					font-size: 24rpx;
					color: #666;
					height: 60rpx;
					line-height: 60rpx;
				}

				.num {
					font-size: 24rpx;
					color: #666;
				}
			}
		}
	}

	.m-title {
		height: 80rpx;
		line-height: 80rpx;
		color: #333;
		font-size: 32rpx;

		text {
			margin-left: 10rpx;
			font-size: 24rpx;
			color: @color;
		}
	}

	.main {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 10rpx;

		.p {
			line-height: 40rpx;
			font-size: 24rpx;
			color: #333;

			text {
				width: 150rpx;
				margin-right: 30rpx;
			}
		}
	}

	.select-address {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 10rpx;
		text-align: center;
		color: @color;
		font-size: 28rpx;
		margin-bottom: 30rpx;
	}
}
</style>
